import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TCPClient {

    private static final String SERVER_ADDRESS = "127.168.124.252";
    private static final int PORT = 9000;

    public static void main(String[] args) {
        try {
            fileClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void fileClient() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你要上传的文件路径：");
        String filename = sc.next();

        // 文件检查
        File file = new File(filename);
        if (!file.exists()) {
            System.out.println("文件不存在，请检查路径！");
            return;
        }

        try (Socket socket = new Socket(InetAddress.getByName(SERVER_ADDRESS), PORT);
             FileInputStream fis = new FileInputStream(file);
             OutputStream os = socket.getOutputStream()) {

            // 发送文件名给服务器
            DataOutputStream dataOutputStream = new DataOutputStream(os);
            dataOutputStream.writeUTF(file.getName());

            // 发送文件内容
            byte[] buffer = new byte[1024];
            int len;
            int totalBytesSent = 0;
            System.out.println("开始上传文件...");

            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                totalBytesSent += len;

                // 输出进度
                double progress = (double) totalBytesSent / file.length() * 100;
                System.out.printf("上传进度: %.2f%%\r", progress);
            }

            System.out.println("\n文件上传完成，等待服务器响应...");

            // 关闭输出流，告知服务器文件发送完毕
            socket.shutdownOutput();

            // 接收服务器的响应
            try (InputStream inputStream = socket.getInputStream();
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

                byte[] buffer2 = new byte[1024];
                int len2;
                while ((len2 = inputStream.read(buffer2)) != -1) {
                    baos.write(buffer2, 0, len2);
                }
                System.out.println("服务器回复: " + baos.toString());
            }
        } catch (IOException e) {
            System.err.println("上传文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
